﻿using Microsoft.Extensions.DependencyInjection;
using SBlogCore.Common.Helpers;
using SBlogCore.Common.Utilities.Extension;
using SqlSugar;

namespace SBlogCore.Common.DatabaseAccessor.Extend
{
    public static class SqlSugerExtensions
    {
        [SkipScan]
        public static void AddSqlSugerSetUp(this IServiceCollection Services)
        {
            ConnectionConfig ConnectConfig = new ConnectionConfig()
            {
                ConnectionString = AppSetting.ReadAppSettings("ConnectionStrings:SBlogCore"),
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, p) =>
                    {
                        Parallel.For(0, 1, e =>
                        {
                            ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", "【SQLSuger语句】：" + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan);

                        });
                    },
                },
                MoreSettings = new ConnMoreSettings()
                {
                    //IsWithNoLockQuery = true,
                    IsAutoRemoveDataCache = true
                }
            };
            Services.AddScoped<ISqlSugarClient>(w =>new SqlSugarScope(ConnectConfig));
        }
        private static string GetWholeSql(SugarParameter[] paramArr, string sql)
        {
            foreach (var param in paramArr)
            {
                sql.Replace(param.ParameterName, param.Value.ObjToString());
            }

            return sql;
        }
    }
}
